package apresentacao.caminhoneiro;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import dao.caminhoneiro.AsyncTask_Meu_Perfil;
import dao.caminhoneiro.AsyncTask_Meus_Fretes;
import dao.caminhoneiro.AsyncTask_Meus_Lances;
import dao.caminhoneiro.NotifyExecutor;
import dao.caminhoneiro.NotifyRunnable;
import entidade.caminhoneiro.Caminhoneiro;
import entidade.caminhoneiro.Local;
import tcc.caminhoneiro.R;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_Menu_Principal extends ActionBarActivity implements OnItemClickListener{

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private int notification_time;
    private int raio;
    
    public static Integer user_id = null;

    public static boolean isNotifyOn = false;
  
    public static boolean isGPSOn = false;
    
    public static Location localAtual = null;
    
	ListView lvListView;
	
	String[] menu = {"Meu Perfil", "Meus Lances", "Meus Fretes", "Buscar Frete", "Ajustes", "Sair"};
	
	boolean flag;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu_principal);
		inicializar();
		
		verifyGPS();
		openNotificationThread();
		if (hasNotification()) loadNotification();
		else loadHome();
		
		//Toast.makeText(getActivity(), "clique", Toast.LENGTH_SHORT).show();
	}
	
	//Toast.makeText(getBaseContext(), charge, Toast.LENGTH_SHORT).show();
	/*
	 * Verifica se a notificacao de novo frete foi apertada. A verificacao eh feita checando o intent.
	 */
	private boolean hasNotification(){
		
		Intent cIntent = getIntent();
		Bundle bIntent = null;
		String charge = null;
		if (cIntent!=null){
			bIntent = cIntent.getExtras();
			if (bIntent != null){
				charge = bIntent.getString("campos");
				if (charge !=null) return true;
			}
		}
		return false;
	}
	
	//Toast.makeText(getBaseContext(), "charge", Toast.LENGTH_SHORT).show();
	/*
	 * Insere fragment de notificacoes
	 */
	private void loadNotification(){
		Fragment_ResultActivity fragment_res = new Fragment_ResultActivity();
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_principal_llFragment, fragment_res).commit();
	}
	
	/*
	 * Abre thread de verificacao de notificacoes se nao foi aberto
	 */
	private void openNotificationThread(){
		if (!isNotifyOn){
		    NotifyExecutor notifyExecutor = new NotifyExecutor();
			notifyExecutor.execute(new NotifyRunnable(this, getNotificationTime(), getRaio() ) );
			isNotifyOn = true;
		}
	}
	
	private void loadHome(){
		AsyncTask_Meu_Perfil async = new AsyncTask_Meu_Perfil(Activity_Menu_Principal.this);
		async.execute();
	}

	
	private int getRaio(){
		String FILENAME = "notificationRaio.txt";

		File file = getBaseContext().getFileStreamPath(FILENAME);
        
		if (file.exists()) {
			return readFile(FILENAME, 10000);
		}else{
			//raio=quantidade=posicao
			write(FILENAME, "raio=10000=0");		
		}

		return 10000;
	}
	
	private int getNotificationTime(){
		String FILENAME = "notificationTime.txt";

		File file = getBaseContext().getFileStreamPath(FILENAME);
        
		if (file.exists()) {
			return readFile(FILENAME, 10);
		}else{
			write(FILENAME, "time=10=0");	
			return 10;
		}
	}
	
	private int readFile(String file, int err){
		StringBuffer strBf = new StringBuffer("");
		String readString = "";
		try {
			FileInputStream fIn = openFileInput ( file ) ;
            InputStreamReader isr = new InputStreamReader ( fIn ) ;
            BufferedReader buffreader = new BufferedReader ( isr ) ;

            readString = buffreader.readLine();
            strBf.append(readString);
            /*
            while ( readString != null ) {
                strBf.append(readString);
                readString = buffreader.readLine ( ) ;
                break;
            }
            */
            
            buffreader.close();
            isr.close ( ) ;
            fIn.close();
            return Integer.valueOf(strBf.toString().split("=")[1]);
            
		} catch (Exception e) {
			e.printStackTrace();
		}
		return err;
	}
	
private void write(String file, String content){
		
		FileOutputStream fos;
		try {
			fos = openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(content.getBytes());
			fos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	private void verifyGPS(){
		if (!isGPSOn){
			isGPSOn = true;
			Local tracker = new Local(getBaseContext());
			tracker.startGPS();
		}
	}
	
	public void inicializar(){
		lvListView 				= (ListView) findViewById(R.id.menu_principal_lvListView);
        drawerLayout 			= (DrawerLayout) findViewById(R.id.drawer_layout);
        actionBarDrawerToggle 	= new ActionBarDrawerToggle(this, drawerLayout, R.drawable.truck, R.string.drawer_open, R.string.drawer_close);
        
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.white)));
        getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        drawerLayout.setDrawerListener(actionBarDrawerToggle); 
		lvListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,menu));
        lvListView.setOnItemClickListener(this);
	}
	
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    	if(!flag){
         actionBarDrawerToggle.syncState();
    	}
    }
 
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		switch (position) {
			case 0:{
				AsyncTask_Meu_Perfil async = new AsyncTask_Meu_Perfil(Activity_Menu_Principal.this);
				async.execute();
				break;
			}
			case 1:{
				AsyncTask_Meus_Lances async = new AsyncTask_Meus_Lances(Activity_Menu_Principal.this);
				async.execute();
				break;
			}			
			case 2:{
				AsyncTask_Meus_Fretes async = new AsyncTask_Meus_Fretes(Activity_Menu_Principal.this);
				async.execute();
				break;
			}
			case 3:{
				Fragment_Menu_Buscas fragment = new Fragment_Menu_Buscas();
				getSupportFragmentManager().beginTransaction().replace(R.id.menu_principal_llFragment, fragment).commit();			
				break;
			}
			case 4:{
				Fragment_Ajustes fragment = new Fragment_Ajustes();
				getSupportFragmentManager().beginTransaction().replace(R.id.menu_principal_llFragment, fragment).commit();			
				break;
			}
			case 5:{
				finish();
				NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
				notificationManager.cancel(NotifyRunnable.FRETE_ID);
				//System.exit(0);
				android.os.Process.killProcess(android.os.Process.myPid());
				break;
			}
		}
		drawerLayout.closeDrawer(lvListView);
	}
}